import apiClient from './config'
import type { 
  Role, 
  CreateRoleRequest, 
  UpdateRoleRequest, 
  RoleListParams,
  ApiResponse,
  PaginatedResponse 
} from './types'

export const rolesApi = {
  // 获取角色列表
  getRoles: (params?: RoleListParams): Promise<ApiResponse<PaginatedResponse<Role>>> => {
    return apiClient.get('/roles', { params })
  },

  // 获取所有角色（不分页）
  getAllRoles: (): Promise<ApiResponse<Role[]>> => {
    return apiClient.get('/roles/all')
  },

  // 获取角色详情
  getRole: (id: number): Promise<ApiResponse<Role>> => {
    return apiClient.get(`/roles/${id}`)
  },

  // 创建角色
  createRole: (data: CreateRoleRequest): Promise<ApiResponse<Role>> => {
    return apiClient.post('/roles', data)
  },

  // 更新角色
  updateRole: (data: UpdateRoleRequest): Promise<ApiResponse<Role>> => {
    return apiClient.put(`/roles/${data.id}`, data)
  },

  // 删除角色
  deleteRole: (id: number): Promise<ApiResponse<any>> => {
    return apiClient.delete(`/roles/${id}`)
  },

  // 批量删除角色
  batchDeleteRoles: (ids: number[]): Promise<ApiResponse<any>> => {
    return apiClient.delete('/roles/batch', { data: { ids } })
  },

  // 更新角色状态
  updateRoleStatus: (id: number, status: 'active' | 'inactive'): Promise<ApiResponse<any>> => {
    return apiClient.patch(`/roles/${id}/status`, { status })
  },

  // 获取角色权限
  getRolePermissions: (id: number): Promise<ApiResponse<any[]>> => {
    return apiClient.get(`/roles/${id}/permissions`)
  },

  // 分配角色权限
  assignRolePermissions: (id: number, permissionIds: number[]): Promise<ApiResponse<any>> => {
    return apiClient.post(`/roles/${id}/permissions`, { permissionIds })
  },

  // 获取角色用户
  getRoleUsers: (id: number, params?: { page?: number; pageSize?: number }): Promise<ApiResponse<PaginatedResponse<any>>> => {
    return apiClient.get(`/roles/${id}/users`, { params })
  },

  // 复制角色
  copyRole: (id: number, newName: string): Promise<ApiResponse<Role>> => {
    return apiClient.post(`/roles/${id}/copy`, { name: newName })
  },

  // 检查角色代码是否可用
  checkRoleCode: (code: string, excludeId?: number): Promise<ApiResponse<{ available: boolean }>> => {
    return apiClient.get('/roles/check-code', { 
      params: { code, excludeId } 
    })
  }
}